package sf.member.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by ligen on 16-3-7.
 */

import com.pingplusplus.model.Charge;

import sf.core.exception.SugarException;
import sf.core.mapper.TfOrderMapper;
import sf.core.service.AuthService;
import sf.core.service.PaymentService;
import sf.core.util.NumberUtil;
import sf.member.vo.Order;
import sf.member.vo.Result;

@RequestMapping("/charge")
@RestController
public class ChargeController {

	@Resource
	TfOrderMapper orderMapper;

	@Resource
	PaymentService paymentService;

	@Resource
	AuthService<Integer> authService;

	@RequestMapping("")
	public Charge charge(HttpServletRequest request, @RequestParam int amount, @RequestParam String channel,
			@RequestParam int deviceType, @RequestParam(required = false) String subject,
			@RequestParam(required = false) String openId) throws SugarException {
		Integer uid = authService.getSubject(request);
		Order order = new Order(uid, amount, paymentService.getUnitPrice() * amount, System.currentTimeMillis(),
				StringUtils.isEmpty(subject) ? String.format("%s颗糖豆", amount) : subject);
		orderMapper.insert(order.toPo());
		return paymentService.charge(order.getCost() * NumberUtil.ONE_HUNDRED_INT, channel, order.getSn(),
				order.getSubject(), deviceType, openId);
	}

	@RequestMapping("/howMuch")
	public Result<Integer> calc(@RequestParam int amount) {
		return new Result<>(amount * paymentService.getUnitPrice());
	}

}
